package com.xinghen.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinghen.security.core.SecurityResult;
import com.xinghen.security.core.properties.LoginResponseType;
import com.xinghen.security.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xinghen
 * @ClassName: DefaultAuthenticationSuccessHandler
 * @Package: com.xinghen.security.core.authentication
 * @Description 默认的浏览器端认证成功处理器
 * @create 2018-04-18 11:43
 */
@Slf4j
public class DefaultAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private SecurityProperties securityProperties;

    private RequestCache requestCache = new HttpSessionRequestCache();

    public DefaultAuthenticationSuccessHandler(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        log.info("登录成功");
        if (StringUtils.equalsIgnoreCase(LoginResponseType.JSON.name(),
                securityProperties.getBrowser().getSignInResponseType().name())) {
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write(new ObjectMapper().writeValueAsString(SecurityResult.ok()));
        } else {
            // 如果设置了singInSuccessUrl，总是跳到设置的地址上
            // 如果没设置，则尝试跳转到登录之前访问的地址上，如果登录前访问地址为空，则跳到网站根路径上
            if (StringUtils.isNotBlank(securityProperties.getBrowser().getSingInSuccessUrl())) {
                requestCache.removeRequest(request, response);
                setAlwaysUseDefaultTargetUrl(true);
                setDefaultTargetUrl(securityProperties.getBrowser().getSingInSuccessUrl());
            }
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
